<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\mongo\MongoOeVideoModel;
use app\model\OeSchemaUrlModel;
use app\model\OeSchemaVideoModel;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use MongoDB\BSON\Regex;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class SchemaVideoService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['schema_video'];

    /**
     * 拉取数据.
     * @param string $keyStr redis队列信息
     */
    public static function getVideoList(string $keyStr = ''): bool
    {
        $key = explode('_', $keyStr);
        if (count($key) < 3) {
            return self::setError('队列信息错误');
        }
        $accountId = intval($key[0]);
        $id = strval($key[1]);
        $type = intval($key[2]);
        Db::startTrans();
        try {
            $data = [];
            $num = 0;
            $schemaUrlId = 0;
            if ($type == 1) {
                $schemaUrl = self::getSchemaUrl($id);
                if (! $schemaUrl instanceof OeSchemaUrlModel || ! $schemaUrl->getKey()) {
                    throw new \Exception('直达链接信息获取失败');
                }
                $where = [];
                $where[] = ['material_properties', 'not in', ['INEFFICIENT_MATERIAL', 'AD_LOW_QUALITY_MATERIAL']];
                $where[] = ['account_id', '=', $accountId];
                $where[] = ['is_delete', '=', 0];
                // 查询匹配的
                $videoData = (new MongoOeVideoModel())
                    ->where($where)
                    ->where('filename', new Regex('^' . $schemaUrl->getAttr('link_name'), 'i'))
                    ->select()
                    ->toArray();
                if ($videoData) {
                    foreach ($videoData as $video) {
                        $arr = explode('-', $video['filename']);
                        $code = $arr[0] ?? '';
                        if ($code != $schemaUrl->getAttr('link_name')) {
                            continue;
                        }

                        $data[] = [
                            'schema_url_id' => $id,
                            'account_id' => $accountId,
                            'video_id' => $video['video_id'],
                            'video_type' => $video['width'] > $video['height'] ? OceanEnum::CREATIVE_IMAGE_MODE_VIDEO : OceanEnum::CREATIVE_IMAGE_MODE_VIDEO_VERTICAL,
                            'create_time' => time(),
                        ];
                    }
                    $num = count($data);
                }
                $schemaUrlId = $id;
            } else {
                $video = (new MongoOeVideoModel())->where('account_id', $accountId)
                    ->whereNotIn('material_properties', ['INEFFICIENT_MATERIAL', 'AD_LOW_QUALITY_MATERIAL'])
                    ->where('video_id', $id)
                    ->find();
                if ($video) {
                    $code = explode('-', $video['filename'])[0];
                    if ($code) {
                        $urlData = (new OeSchemaUrlModel())->where('account_id', $accountId)
                            ->where('link_name', $code)->find();
                        if ($urlData) {
                            $data[] = [
                                'schema_url_id' => $urlData['id'],
                                'account_id' => $accountId,
                                'video_id' => $video['video_id'],
                                'video_type' => $video['width'] > $video['height'] ? OceanEnum::CREATIVE_IMAGE_MODE_VIDEO : OceanEnum::CREATIVE_IMAGE_MODE_VIDEO_VERTICAL,
                                'create_time' => time(),
                            ];
                            $num = 1;
                            $schemaUrlId = $urlData['id'];
                        }
                    }
                }
            }

            if (! empty($data)) {
                if (! (new OeSchemaVideoModel())->insertAll($data)) {
                    throw new \Exception('保存信息出错');
                }
                if ($schemaUrlId) {
                    if (! (new OeSchemaUrlModel())->where('id', $schemaUrlId)->inc('video_num', $num)->update()) {
                        throw new \Exception('修改视频数量出错');
                    }
                }
            }

            if ($type == 1 && ! (new OeSchemaUrlModel())->where('id', $schemaUrlId)->update(['is_sync_video' => 1])) {
                throw new \Exception('修改状态出错');
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 拉取直达链接信息.
     * @param string $id 主键id
     * @return bool|mixed|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getSchemaUrl(string $id = '')
    {
        return (new OeSchemaUrlModel())->where('id', $id)->find();
    }
}
